package com.dwjm.exam.admin;

import com.google.gson.Gson;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@WebServlet("/admin/login")
public class AdminLoginHandler extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("application/json;charset=utf-8");
        resp.setCharacterEncoding("utf-8");
        req.setCharacterEncoding("utf-8");

        String username = req.getParameter("username");
        String password = req.getParameter("password");

        AdminDaoImpl adminDao = new AdminDaoImpl();
        Admin admin = adminDao.login(username, password);
        
        PrintWriter out = resp.getWriter();
        Map<String, Object> responseMap = new HashMap<>();
        
        if (admin != null) {
            // 登录成功，更新最后登录时间
            Date now = new Date();
            adminDao.updateLastLoginTime(admin.getAdminId(), now);
            
            // 准备返回数据
            Map<String, Object> adminData = new HashMap<>();
            adminData.put("adminId", admin.getAdminId());
            adminData.put("username", admin.getUsername());
            adminData.put("realName", admin.getRealName());
            adminData.put("role", admin.getRole());
            
            responseMap.put("code", 200);
            responseMap.put("msg", "登录成功");
            responseMap.put("data", adminData);
        } else {
            // 登录失败
            responseMap.put("code", 400);
            responseMap.put("msg", "用户名或密码错误");
        }
        
        // 转换为JSON并输出
        Gson gson = new Gson();
        String json = gson.toJson(responseMap);
        out.write(json);
        out.flush();
        out.close();
    }
} 